import redis.asyncio as redis


class RedisSingleton:
    _pool: redis.ConnectionPool = None

    @classmethod
    async def get_client(cls, db: int = 0) -> redis.Redis:
        """获取全局唯一的 Redis 客户端（连接池复用）"""
        if not cls._pool:
            cls._pool = redis.ConnectionPool.from_url(
                "redis://192.168.43.123:6379",
                decode_responses=True,  # 自动解码字符串
                max_connections=10,  # 连接池大小
                db=db  # 指定数据库索引
            )
        return redis.Redis(connection_pool=cls._pool)

    @classmethod
    async def close(cls):
        """关闭连接池（在应用关闭时调用）"""
        if cls._pool:
            await cls._pool.disconnect()
